<?php

namespace App\depository;

use App\Enum\CommonEnum;
use App\Enum\TeamsEnum;
use App\Models\ManageMapExtraModel;
use App\Models\ManageMapModel;

class ManageMapDep
{
    public $model;

    public function __construct()
    {
        $this->model = new ManageMapModel();
    }

    public function first($id){
        return $this->model->where('id', $id)->first();
    }

    public function list($param)
    {
        $res = $this->model
            ->when(!empty($param['id']), function ($query) use ($param) {
                return $query->where("id",$param['id']);
            })
            ->when(!empty($param['map_name']), function ($query) use ($param) {
                return $query->where("map_name", 'like', "%{$param['map_name']}%");
            })
            ->when(!empty($param['zh_name']), function ($query) use ($param) {
                return $query->where("zh_name", 'like', "%{$param['zh_name']}%");
            })
            ->orderBy('id', 'desc')
            ->paginate($param['per_page'], ['*'], 'page', $param['current_page']);;
        return $res;
    }

    public function subList($teamId,$param){
        $extraTable = (new ManageMapExtraModel())->getTable();
        $table = $this->model->getTable();

        $res = $this->model->leftJoin($extraTable,function($join) use ($teamId,$table,$extraTable){
                              $join->on("{$table}.id","=","{$extraTable}.manage_map_id");
                              $join->where("{$extraTable}.gh_id",$table);
                            })
                            ->select(["{$extraTable}.extra","{$table}.map_name","{$table}.zh_name","{$table}.id as map_id"])
                            ->where("{$extraTable}.gh_id",$teamId)
                            ->orWhere("{$extraTable}.gh_id",null)
                            ->orderBy("{$table}.id", 'desc')
                            ->paginate($param['per_page'], ['*'], 'page', $param['current_page']);

        return $res;

    }


    public function add($data)
    {
        $res = $this->model->insert($data);
        return $res;
    }

    public function upd($id, $data)
    {
        $res = $this->model->where('id', $id)->update($data);
        return $res;
    }

    public function del($id)
    {
        $res = $this->model->where('id', $id)->delete();
        return $res;
    }

}
